package com.bed.lovewithpatientbed.core.aop;

import com.bed.lovewithpatientbed.core.HttpContextUtil;
import com.bed.lovewithpatientbed.core.annocation.LogAnno;
import com.bed.lovewithpatientbed.dao.LogDao;
import com.bed.lovewithpatientbed.pojo.Log;
import com.bed.lovewithpatientbed.pojo.WorkerMessage;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.lang.reflect.Method;
import java.util.Date;

/**
 * @author Tyl
 * @version 1.0.0
 * @ClassName logAopAspect.java
 * @Description aop实现日志
 * @createTime 2020年10月21日 16:08:00
 */
@Order(3)
@Component
@Aspect
public class logAopAspect {
    @Resource
    private LogDao logDao;
    /**
     * @description 环绕通知记录日志通过注解配置需要增加日志功能的方法
     * @author tyl
     * @updateTime 2020/10/21 16:10 
     * @param
     */
      @Around("@annotation(com.bed.lovewithpatientbed.core.annocation.LogAnno)")
      public Object aroundAdvice(ProceedingJoinPoint pjp){
          /*1、方法执行前处理，相当于前置通知*/
          /*获取方法签名*/
          MethodSignature methodSignature = (MethodSignature)pjp.getSignature();
          /*获取方法*/
          Method method = methodSignature.getMethod();
          /*获取方法上面的注解*/
          LogAnno logAnno = method.getAnnotation(LogAnno.class);
          /*获取操作描述的属性值*/
          String operateType = logAnno.operateType();
          /*创捷一个新的日志对象*/
          Log log = new Log();
          /*操作说明*/
          log.setOperatetype(operateType);
          /*设置操作人*/
          ServletRequestAttributes attr = (ServletRequestAttributes) RequestContextHolder.currentRequestAttributes();
          HttpSession session=attr.getRequest().getSession(true);
          WorkerMessage workerMessage = (WorkerMessage) session.getAttribute("workerMessage");
          log.setOperateor(workerMessage.getWorkMessagePhone());
          /*获得ip*/
          String ip = HttpContextUtil.getIpAddress();
          log.setIp(ip);
          Object result = null;
          /*执行代理方法*/
          try {
              result = pjp.proceed();
              /*2、方法执行成功后会走到这一步*/
              log.setOperateresult("正常");
          } catch (Throwable throwable) {
              throwable.printStackTrace();
              /*3、异常通知*/
             log.setOperateresult("失败");
          }finally {
              /*4、最终通知*/
              log.setOperatedate(new Date());
              logDao.insert(log);
          }
          return result;
      }
}
